<?php
/**
 * 标签管理
 * $Id: class.tag.php 238 2011-01-13 08:53:47Z bwanglei@gmail.com $
 */

class awTag {
	/**
	 * 内部数据对象
	 * @var MySQL
	 */
	private $db;

	function __construct() {
		$this->db = MySQL::getInstance();
	}

	/**
	 * 获取标签
	 *
	 * @param int $id
	 * @return array
	 */
	function getTag($blogId ='') {
		$tags = array();
		if ($blogId == '') return false;
		$result = $this->db->query('SELECT * FROM `'.DB_PREFIX.'tags` WHERE aid='.$blogId);
		while($row = $this->db->fetch_array($result)) {
			$tags[] = $row['tag'];
		}
		return $tags;
	}

	/**
	 * 取得某个标签下的所有帖子ID
	 */
	function get_tag_ids($tag) {
		$sql = 'SELECT `aid` FROM `'.DB_PREFIX.'tags` WHERE `tag`=\''.$tag.'\'';
		$result = $this->db->query($sql);
		$array_ids = array();
		while ($echo_row = $this->db->fetch_array($result)) {
			$array_ids[] = $echo_row['aid'];
		}
		return $array_ids;
	}

	function getAidByTagName($tagName) {
		$aids = array();
		$res = $this->db->query('SELECT aid FROM `'.DB_PREFIX.'tags` WHERE tag='.$tagName);
		while($row = $this->db->fetch_array($res)) {
			$aids[] = $row['aid'];
		}
		return $aids;
	}

	/**
	 * 添加标签
	 *
	 * @param string $tagStr
	 */
	function addTag($tags,$blogId) {
		foreach ($tags as $tagName) {
			$result = $this->db->once_fetch_array('SELECT * FROM `'.DB_PREFIX.'tags` WHERE tag=\''.$tagName.'\' AND aid='.$blogId);
			if (empty($result)) {
				$query = 'INSERT INTO `'.DB_PREFIX.'tags` (`aid`,`tag`) VALUES('.$blogId.',\''.$tagName.'\')';
				$this->db->query($query);
			}
		}
	}

	/**
	 * 更新标签
	 *
	 * @param string $tagStr
	 * @param int $blogId
	 */
	function updateTag($tags, $blogId) {
		$old_tags = array();
		$query = $this->db->query('SELECT `tag` FROM `'.DB_PREFIX.'tags` WHERE aid='.$blogId);
		while ($row = $this->db->fetch_array($query)) {
			$old_tags[] = $row['tag'];
		}
		//取得要删除的标签名称的集合
		$delTagName = array_diff($old_tags, $tags);
		//取得要添加的标签名称结合
		$addTagName = array_diff($tags, $old_tags);
		if (!empty($delTagName)) {
			$strDTN = '';
			foreach ($delTagName as $oneDTN) {
				if ($strDTN == '') {
					$strDTN .= '\''.$oneDTN.'\'';
				} else {
					$strDTN .= ',\''.$oneDTN.'\'';
				}
			}
			$this->db->query('DELETE FROM `'.DB_PREFIX.'tags` WHERE `aid`='.$blogId.' AND `tag` in ('.$strDTN.')');
		}
		if (!empty($addTagName)) {
			$strATN = '';
			foreach ($addTagName as $oneATN) {
				if ($strATN == '') {
					$strATN .= '('.$blogId.',\''.$oneATN.'\')';
				} else {
					$strATN .= ',('.$blogId.',\''.$oneATN.'\')';
				}
			}
			$this->db->query('INSERT INTO `'.DB_PREFIX.'tags` (`aid`,`tag`) VALUES '.$strATN);
		}
	}

	function updateTagName($oldTagName, $tagName) {
		$sql = 'UPDATE `'.DB_PREFIX.'tags` SET `tag`=\''.$tagName.'\' WHERE `tag`=\''.$oldTagName.'\'';
		$this->db->query($sql);
	}

	function deleteTag($tagName) {
		$sql = 'DELETE FROM `'.DB_PREFIX.'tags` WHERE `tag`=\''.$tagName.'\'';
		$this->db->query($sql);
	}
}
